package com.sofa.shark.file.uitls;

import com.alibaba.nacos.common.util.UuidUtils;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import org.springframework.util.ClassUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author tonyp
 * @description 文件相关操作类
 * @date 2020.4.3
 */
@UtilityClass
public class FileUtils {
    /*** multipartFile转file
     * @param multipartFile
     * @return File
     */
    public  File getFile(MultipartFile multipartFile, String tempPath) {
        String type = "";
        if (multipartFile.getOriginalFilename().indexOf(".") != -1) {
            type = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".") + 1);
        }
        Long time = System.currentTimeMillis();
        String uuid = UuidUtils.generateUuid();
        String fileName = uuid + time + "." + type;
        String filePath = tempPath;
        File file = new File(filePath + fileName);
        try {
            multipartFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }
    /**
     * 获取项目类路径
     * */
    public String getClassPath(){
       return ClassUtils.getDefaultClassLoader().getResource("").getPath();
    }

    /**
     * 获取项目资源路径
     * */
    @SneakyThrows
    public String getResourcePath(){
        return  ResourceUtils.getURL("classpath:").getPath();
    }
}
